<template>
	<gui-page ref="guiPage" :customHeader="true">
		<template v-slot:gHeader>
			<nav-bar-custom left-icon="left" :title="$t('multilingual.barcodeMerge')"></nav-bar-custom>
		</template>
		<template v-slot:gBody>
			<view class="page-auto" :style="'height: calc(100vh - '+ navHeight +'px);'">
				<!-- 扫描和拆分 -->
				<view class="gui-bg-white gui-dark-bg-level-3 gui-padding-x distributed-head">
					<view class="custom-card-title">
						<text class="title-line"></text>
						{{$t('multilingual.materialBarcodeInfo')}}
					</view>
					<view class="gui-form-item gui-border-b" style="padding: 20rpx 0;">
						<text class="item-info-title" style="padding-right: 40rpx;">
							<text class="required-color">*</text>
							{{$t('distributedEnter.materialCoded')}}
						</text>
						<uni-easyinput type="search" :focus="data.isfocus" class="uni-mt-5" suffixIcon="scan" v-model="data.oddNum"
							:placeholder="$t('multilingual.scanBarcodeInfo')" @confirm="confirm" @iconClick="iconClick">
						</uni-easyinput>
					</view>
				</view>
				<!-- 物料信息和拆分详情 -->
				<scroll-view :show-scrollbar="false" :scroll-y="true" class="scroll">
					<view style="height:2rpx"></view>
					<view class="custom-form-card gui-relative" v-if="Object.keys(data.newBarcodeInfo).length !== 0">
						<view class="custom-card-title">
							<text class="title-line"></text>
							{{$t('multilingual.mergeBarcodeInfo')}}
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>
							{{data.newBarcodeInfo.materialName}}
						</view>
						<view class="custom-card-itemOne">
							<text
								class="item-info-title">{{$t('distributedEnter.materialCoded')}}：</text>{{data.newBarcodeInfo.barcode}}
						</view>
						<view class="custom-card-itemOne">
							<text
								class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{data.newBarcodeInfo.materialSpec}}
						</view>
						<view class="custom-card-itemOne">
							<text
								class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{data.newBarcodeInfo.materialCode}}
						</view>
						<view class="custom-card-itemOne">
							<view class="card-item-50">
								<text
									class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{data.newBarcodeInfo.currentQty}}
							</view>
							<view class="card-item-50">
								<text
									class="item-info-title">{{$t('distributedEnter.uom')}}：</text>{{data.newBarcodeInfo.unit}}
							</view>
						</view>
						<view class="custom-card-itemOne">
							<text
								class="item-info-title">{{$t('translationImage.currentWarehouse')}}：</text>{{data.newBarcodeInfo.warehouseCode}}
						</view>
						<view class="custom-card-itemOne">
							<text
								class="item-info-title">{{$t('translationImage.currentLocation')}}：</text>{{data.newBarcodeInfo.locationCode}}
						</view>
						<view class="custom-card-itemOne gui-flex gui-justify-content-end" style="height: 80rpx;">
							<view class="print-class" @click="printsLabelsFn">
								{{$t('multilingual.printBarcode')}}
							</view>
						</view>
					</view>
					<view class="custom-form-card gui-relative" v-for="(x,i) in  data.barcodeList" :key="x.id">
						<uni-icons class="close-icons" style="right: 20rpx;top: 20rpx;" type="closeempty"
							color="#9C9C9C" size="30" @click="deleteItem(i)"></uni-icons>
						<view class="custom-card-title">
							<text class="title-line"></text>
							{{$t('finishedInventory.barcodeInformation')}}
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{$t('distributedEnter.materialName')}}：</text>
							{{x.materialName}}
						</view>
						<view class="custom-card-itemOne">
							<text class="item-info-title">{{$t('distributedEnter.materialCoded')}}：</text>{{x.barcode}}
						</view>
						<view class="custom-card-itemOne">
							<text
								class="item-info-title">{{$t('distributedEnter.materialSpec')}}：</text>{{x.materialSpec}}
						</view>
						<view class="custom-card-itemOne">
							<text
								class="item-info-title">{{$t('distributedEnter.materialCode')}}：</text>{{x.materialCode}}
						</view>
						<view class="custom-card-itemOne">
							<view class="card-item-50">
								<text class="item-info-title">{{$t('distributedEnter.qty')}}：</text>{{x.currentQty}}
							</view>
							<view class="card-item-50">
								<text class="item-info-title">{{$t('distributedEnter.uom')}}：</text>{{x.unit}}
							</view>
						</view>
						<view class="custom-card-itemOne">
							<text
								class="item-info-title">{{$t('translationImage.currentWarehouse')}}：</text>{{x.warehouseCode}}
						</view>
						<view class="custom-card-itemOne">
							<text
								class="item-info-title">{{$t('translationImage.currentLocation')}}：</text>{{x.locationCode}}
						</view>
						<view class="custom-card-itemOne gui-justify-content-end" style="padding: 20rpx;">
							{{$t('multilingual.combineInto')}}：
							<switch :checked="x.mergeNow" style="transform:scale(0.7)"
								@change="switchChange($event,i)" />
						</view>
					</view>
				</scroll-view>
				<!-- 底部操作栏 -->
				<view class="page-bottom-box">
					<view class="page-bottomBtn bottomBtn-bgcolor-green" @click="mergeBarcode">
						{{$t('translationImage.merge')}}</view>
				</view>
			</view>
		</template>
	</gui-page>
</template>

<script setup>
import {
	reactive,
	ref,
	onMounted,
	computed
} from 'vue';
import { BIGBARCODER_PRINT } from '@/constant/index.js'
import {
	selectWmsBarcodeInfoWms,
	mergeBarcodeApi,
	printsLabels1
} from '@/api/api.js'
import { getDataDictionaryFn } from '@/utils/index.js'
import pdaScan from '@/hooks/pdaScan.js'
import { basPdaOperationLogFn } from '@/utils/index.js';
import { OPERATION_MERGING, OPERATION_SCAN,OPERATION_PRINT } from '@/constant/index.js'
import {  PRINT_BASE_URL } from "@/constant/config.js"
import { onShow } from '@dcloudio/uni-app';
import {
	useStore
} from "vuex";

//JS国际化引入
import { useI18n } from 'vue-i18n';
//打印机地址
let printUrl=PRINT_BASE_URL
const {
	scan
} = pdaScan()
const { t } = useI18n();

let store = useStore();
// 页面底部高度
const navHeight = computed(() => {
	return store.state.navHeight
})

let data = reactive({
	oddNum: '',
	isfocus:false,
	limitNum: 0,//扫描条码限制
	barcodeList: [],
	newBarcodeInfo: {},
	defaultValue: '', //打印机名字
});



onShow(()=>{
	data.defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	if (data.defaultValue == '') {
		// uni.showModal({
		// 	content: t('JsInternational.plsPrinter'),
		// 	showCancel: false,
		// });
		uni.showModal({
			content: t('JsInternational.plsPrinter'),
			showCancel: false,
			confirmText:t('pageTranslation.toSet'),
			success: function (res) {
					if (res.confirm) {
						 uni.navigateTo({
						 	url:'/pages/setting/printer'
						 })
					} else if (res.cancel) {
						
					}
				}
		});
	}
})

onMounted(async () => {
	let limitInfo = await getDataDictionaryFn('BarcodeJoinLimit')
	if (limitInfo.length) {
		data.limitNum = limitInfo[0].value
	}
	console.log(data.limitNum, '---data.limitNum---')
	data.defaultValue = uni.getStorageSync(BIGBARCODER_PRINT) || ''
	// if (data.defaultValue == '') {
	// 	uni.showModal({
	// 		content: t('JsInternational.plsPrinter'),
	// 		showCancel: false,
	// 	});
	// }
	console.log('开始监听PDA扫码')
	uni.$on('scancodedate', (data) => {
		console.log('获取到的code：' + data.code)
		getCode(data.code, 'pda')
	})
	setTimeout(() => {  
		data.isfocus = true
	}, 1000)
})
// 打印
const printsLabelsFn = () => {
	console.log(data.newBarcodeInfo, 'data.newBarcodeInfodata.newBarcodeInfo')
	let parmase = {
		barCode: data.newBarcodeInfo.barcode,
		materialCode: data.newBarcodeInfo.materialCode,
		materialName: data.newBarcodeInfo.materialName,
		specification: data.newBarcodeInfo.materialSpec,
		LocationCode:data.newBarcodeInfo.locationCode,
		produceDate: data.newBarcodeInfo.produceDate ? data.newBarcodeInfo.produceDate.slice(0, 10) : '', // 生产日期
		hostid: data.newBarcodeInfo.equipmentCode || '', //机台
		qty: data.newBarcodeInfo.initQty,
		uuit: data.newBarcodeInfo.unit, //单位
		printerName: data.defaultValue //打印机名字
	}
	uni.showLoading({
		title: t('materials.connecting')
	});
	printsLabels1(parmase).then(res => {
		uni.hideLoading();
		try {
			let inputParameter = JSON.stringify(parmase)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '条码合并'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_PRINT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		console.log(res, 'reessss')
		if (res.status == 200) {
			uni.showToast({ title: t('JsInternational.printSuccessfully'), icon: "none" });
		} else {
			uni.showToast({ title: res.message, icon: "none" });
		}
	}).catch(() => {
		try {
			let inputParameter = JSON.stringify(parmase)
			let returnParameter = '无'
			let operationPicture = '条码合并'
			let callInterface = printUrl+"/print/RawMaterialBarCodePrint"
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: 408,//返回状态
				errorMessage: '请求超时',//错误信息
				isPass: 'N',//是否成功 Y N
				operationType: OPERATION_PRINT
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		uni.showToast({ title: t('materials.printingFailed'), icon: "none" });
		uni.hideLoading();
	})
}
// 合并
const mergeBarcode = () => {
	if (data.barcodeList.length < 2) {
		uni.showToast({
			title: t('JsInternational.moreThan'),
			icon: "none"
		});
		return
	}

	let obj = data.barcodeList.filter(x => x.mergeNow)

	if (obj.length) {
		uni.showModal({
			content: t('JsInternational.toMerge') + ` ${obj[0].barcode}`,
			success: (res) => {
				if (res.confirm) {
					submitInterface()
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	} else {
		uni.showModal({
			content: t('JsInternational.confirmCreat'),
			success: (res) => {
				if (res.confirm) {
					submitInterface()
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
	}
}
// 发起请求
const submitInterface = () => {
	// 添加加载框
	uni.showLoading({
		title: 'loading',
		mask: true
	});
	mergeBarcodeApi(data.barcodeList).then(res => {
		try {
			let inputParameter = JSON.stringify(data.barcodeList)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '条码合并'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_MERGING
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			//隐藏加载框
			uni.hideLoading();
			data.oddNum = '';
			data.barcodeList = []
			data.newBarcodeInfo = res.data
			uni.showToast({
				title: t('JsInternational.merge'),
				icon: "none"
			});
		} else {
			uni.showToast({
				title: res.message,
				icon: "none"
			});
		}
	})
}
// 用户调起相机扫码
const iconClick = async (type) => {
	console.log(type)
	if (type === 'suffix') {
		let code = await scan()
		getCode(code, 'scan')
	}
}
// 用户点击键盘上搜索
const confirm = () => {
	let code = data.oddNum;
	getCode(code, 'keydown')
}
// 获取code
const getCode = (code, type) => {
	if (data.barcodeList.length + 1 > Number(data.limitNum)) {
		uni.showToast({ title: t('materials.barcodeMerging'), icon: "none" });
		return
	}
	let isTrue = data.barcodeList.some(x => x.barcode == code)
	if (isTrue) {
		uni.showToast({ title: t('JsInternational.scanned'), icon: "none" });
		return
	}
	data.oddNum = code
	let parmes = {
		barcode: code,
		selectType: 'splitBarcode'
	}
	selectWmsBarcodeInfoWms(parmes).then(res => {
		try {
			let inputParameter = JSON.stringify(parmes)
			let returnParameter = JSON.stringify(res)
			let operationPicture = '条码合并'
			let callInterface = res.rquestUrl
			let opertionParmes = {
				inputParameter,
				returnParameter,
				operationPicture,
				callInterface,
				responseCode: res.status,//返回状态
				errorMessage: res.message,//错误信息
				isPass: res.status == 200 ? 'Y' : 'N',//是否成功 Y N
				operationType: OPERATION_SCAN
			}
			basPdaOperationLogFn(opertionParmes)
		} catch (error) {
		}
		if (res.status == 200) {
			data.newBarcodeInfo = {}
			res.data.mergeNow = false;
			addListRule(res.data)
		} else {
			uni.showToast({
				title: res.message,
				icon: "none"
			});
		}
	})
}
// 添加数据判断
const addListRule = (itemData) => {
	// 如果数组长度为0直接添加
	if (!data.barcodeList.length) {
		data.barcodeList.push(itemData)
	} else if (itemData.materialCode !== data.barcodeList[0].materialCode) {
		uni.showToast({
			title: t('multilingual.inconsistentOfMaterial'),
			icon: "none"
		});
	} else if (itemData.warehouseCode !== data.barcodeList[0].warehouseCode) {
		uni.showToast({
			title: t('multilingual.inconsistentWarehouse'),
			icon: "none"
		});
	} else {
		data.barcodeList.push(itemData)
	}

}
// 开关切换
const switchChange = (evt, index) => {
	console.log(evt.detail.value)
	console.log(index)
	const {
		value
	} = evt.detail;
	if (!value) {
		data.barcodeList[index].mergeNow = value
	} else {
		data.barcodeList.forEach((x, i) => {
			if (i == index) {
				data.barcodeList[i].mergeNow = true
			} else {
				data.barcodeList[i].mergeNow = false
			}
		})
	}
	console.log(data.barcodeList)
}
// 删除某个条码
const deleteItem = (index) => {
	data.barcodeList.splice(index, 1)
}
</script>


<style lang="scss" scoped>
.barcodeSplitting {
	display: flex;
	flex-direction: column;
	height: calc(100vh - 88rpx);
}

.distributed-head {
	border-bottom-left-radius: 16rpx;
	border-bottom-right-radius: 16rpx;
}

.scroll {
	flex: 1;
	height: 2rpx;
}

.print-class {
	display: inline-block;
	padding: 10rpx 20rpx;
	background-color: chartreuse;
	color: #fff;
	border-radius: 8rpx;
	background: $uni-color-teal;
}
</style>
